﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.Industrial.DAL;
using Zhaoxi.Industrial.Model;
using ZhaoXi.Communication;
using System.Data;
using Zhaoxi.Industrial.Base;
using System.Windows;

namespace Zhaoxi.Industrial.BLL
{
    /// <summary>
    /// 三大架构 业务处理类
    /// </summary>
    internal class IndustrialBLL
    {
        DataAccess res = new DataAccess();
        //获取串口信息
        public DataResult<SerialInfo> InitSerialInfo()
        {
            DataResult<SerialInfo> result = new DataResult<SerialInfo>();
            result.Status = false;
            
            try
            {
                SerialInfo Com_1 = new SerialInfo();
                Com_1.PortName = JsonTool.GetKeyCode("PortName");
                Com_1.BaudBit = int.Parse(JsonTool.GetKeyCode("BaudBit"));
                Com_1.DataBit = int.Parse(JsonTool.GetKeyCode("DataBit"));
                Com_1.parity = (Parity)Enum.Parse(typeof(Parity), JsonTool.GetKeyCode("Parity"),true);
                Com_1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), JsonTool.GetKeyCode("StopBits"),true);

                result.Status = true;
                result.Data = Com_1;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }


            return result;
        }

        //数据映射到Storage对象上
        public DataResult<List<StorageModel>> DataInitStorge() {
            DataResult<List<StorageModel>> result = new DataResult<List<StorageModel>>();
            try
            {
                var temp = res.GetStorage_area();
                result.Data = (from q in temp.AsEnumerable()
                        select new StorageModel 
                        {
                            id = Convert.ToInt32(q.Field<string>("id")),
                            slave_id = q.Field<int>("slave_add"),
                            fun_code = Convert.ToInt32(q.Field<string>("func_code")),
                            start_address = Convert.ToInt32(q.Field<string>("start_reg")),
                            length = Convert.ToInt32(q.Field<string>("length"))
                        }).ToList();//因为有多条数据，所以需要用集合
                result.Status = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        //数据映射到Device对象上
        public DataResult<List<DeviceModel>> DataInitDevice()
        {
            DataResult<List<DeviceModel>> result = new DataResult<List<DeviceModel>>();
            try
            {
                var device_array = res.GetDevices();
                var monitor_array = res.GetMonitor_values();

                List<DeviceModel> device_list = new List<DeviceModel>();
                foreach (var item in device_array.AsEnumerable()) {
                    DeviceModel model = new DeviceModel();
                    device_list.Add(model);

                    model.id = item.Field<string>("d_id");
                    model.name = item.Field<string>("d_name");
                    model.isRunning = true;
                    model.isWarning = false;

                    foreach (var item2 in monitor_array.AsEnumerable().Where(m=>m.Field<string>("d_id") == model.id))
                    {
                        MonitorValuesModel monitorValue = new MonitorValuesModel();
                        model.monitorValues.Add(monitorValue);

                        monitorValue.id= item2.Field<string>("d_id");
                        monitorValue.value_id = item2.Field<string>("value_id");
                        monitorValue.value_name = item2.Field<string>("value_name");
                        monitorValue.storage_area_id = item2.Field<string>("s_area_id");
                        monitorValue.address = item2.Field<int>("address");
                        monitorValue.datatype = item2.Field<string>("data_type");
                        monitorValue.isAlarm = item2.Field<int>("is_alarm") == 1;
                        monitorValue.unit = item2.Field<string>("unit");
                        monitorValue.Valuedes = item2.Field<string>("description");

                        //警告
                        var column = Convert.ToDouble(item2.Field<string>("alarm_hihi"));
                        monitorValue.alarm_hihi = column == null ? 0.0 : column;

                        column = Convert.ToDouble(item2.Field<string>("alarm_high"));
                        monitorValue.alarm_high = column == null ? 0.0 : column;

                        column = Convert.ToDouble(item2.Field<string>("alarm_lolo"));
                        monitorValue.alarm_lolo = column == null ? 0.0 : column;

                        column = Convert.ToDouble(item2.Field<string>("alarm_low"));
                        monitorValue.alarm_low = column == null ? 0.0 : column;


                        monitorValue.ValueStateChanged = (state, msg, d_id) => {
                            try
                            {
                                Application.Current?.Dispatcher.Invoke(() =>
                                {   //如果发现设备的警告列表中有数据，先移除 
                                    var index = model.WarningList.ToList().FindIndex(w => w.D_Id == d_id);
                                    if (index > -1)
                                        model.WarningList.RemoveAt(index);
                                    //检查到报错就塞进设备类的警告列表
                                    if (state != Base.MonitorValueState.OK)
                                    {
                                        model.isWarning = true;
                                        model.WarningList.Add(new WarningMessageModel { D_Id = d_id, D_Message = msg });
                                    }
                                });
                                //如果设备类的warninglist > 0 说明处于警告中 
                                var ss = model.WarningList.Count > 0;   //有警告的情况下 为true 无警告的情况下为false
                                if (model.isWarning != ss) //设备不警告的情况下
                                {
                                    model.isWarning = ss;
                                }
                            }
                            catch { }

                        };
                    }
                }
                result.Status = true;
                result.Data = device_list;
               
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }
    }
}
